package com.sm.appbase.base.basemvp;


import androidx.annotation.NonNull;

import com.sm.appbase.net.base.BaseResult;
import com.sm.appbase.net.base.Optional;
import com.sm.appbase.net.exception.NetErrorException;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * @author azheng
 * @date 2018/4/24.
 * GitHub：https://github.com/RookieExaminer
 * Email：wei.azheng@foxmail.com
 * Description：
 */
public class BasePresenter<V extends BaseView> {
    protected V mView;


    /**
     * 绑定view，一般在初始化中调用该方法
     *
     * @param view view
     */
    public void attachView(V view) {
        this.mView = view;
    }

    /**
     * 解除绑定view，一般在onDestroy中调用
     */

    public void detachView() {
        this.mView = null;
    }

    /**
     * View是否绑定
     *
     * @return
     */
    public boolean isViewAttached() {
        return mView != null;
    }

    protected <T> ObservableSource<Optional<T>> apply(Observable<BaseResult<T>> observable) {
        return observable.compose(new RxTransformer().handle_result())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public class RxTransformer {
        public <T> ObservableTransformer<BaseResult<T>, Optional<T>> handle_result() {
            return upstream -> upstream
                    .flatMap(new Function<BaseResult<T>, ObservableSource<Optional<T>>>() {
                                 @Override
                                 public ObservableSource<Optional<T>> apply(@NonNull BaseResult<T> result) throws Exception {
                                     if (result.getCode() == 1) {
                                         // 将返回结果进行包装
                                         return createHttpData(result.transform());
                                     } else {
                                         // 发送请求失败的信息
                                         return Observable.error(new NetErrorException(result.getMsg(), result.getCode()));
                                     }
//                                     return Observable.empty();
                                 }
                             }
                    );
        }

        public <T> Observable<Optional<T>> createHttpData(Optional<T> t) {

            return Observable.create(e -> {
                try {
                    e.onNext(t);
                    e.onComplete();
                } catch (Exception exc) {
                    e.onError(exc);
                }
            });
        }
    }

}
